package be.sc.classicnetwork.dao.hibernate.interceptor;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import be.sc.classicnetwork.model.AbstractEntity;
import be.sc.classicnetwork.model.User;

/**
 * AuditInterceptor.
 */
public class AuditInterceptor extends EmptyInterceptor {

	/**
	 * @see org.hibernate.EmptyInterceptor#onSave(java.lang.Object,
	 *      java.io.Serializable, java.lang.Object[], java.lang.String[],
	 *      org.hibernate.type.Type[])
	 */
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		// check it's an AbstractEntity
		if (entity instanceof AbstractEntity) {
			Date now = new Date();

			// get the current user
			User currentUser = User.getCurrentUser();

			// set audit properties
			for (int i = 0; i < propertyNames.length; i++) {
				if ("userInfo".equals(propertyNames[i])) {
					state[i] = currentUser.getUserInfo();
				} else if ("lastSavedDate".equals(propertyNames[i])) {
					state[i] = now;
				} else if ("createdBy".equals(propertyNames[i])) {
					state[i] = currentUser.getUsername();
				} else if ("createdDate".equals(propertyNames[i])) {
					state[i] = now;
				}
			}
			return true;
		}
		return false;
	}

	/**
	 * @see org.hibernate.EmptyInterceptor#onFlushDirty(java.lang.Object,
	 *      java.io.Serializable, java.lang.Object[], java.lang.Object[],
	 *      java.lang.String[], org.hibernate.type.Type[])
	 */
	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		// check it's an AbstractEntity
		if (entity instanceof AbstractEntity) {
			Date now = new Date();

			// get the current user
			User currentUser = User.getCurrentUser();

			// set audit properties
			for (int i = 0; i < propertyNames.length; i++) {
				if ("userInfo".equals(propertyNames[i])) {
					currentState[i] = currentUser.getUserInfo();
				} else if ("lastSavedDate".equals(propertyNames[i])) {
					currentState[i] = now;
				}
			}
			return true;
		}
		return false;
	}
}
